from django.db import models
import datetime
import time
from sync.models.sf_object import SFObject
TASK_TIME_CONS=30
class SyncProc(models.Model):
    #syncrhonization check interval
    sync_interval = models.IntegerField(default=20)
    last_sync = models.DateTimeField(null=True,)
    class Meta:
        db_table ="sync_sync_proc"
        app_label = 'sync'
    def run(self):
        while True:
            #self.read_settings()
            self.update_local2sf()
            self.update_sf2local()
            self.last_sync=datetime.datetime.utcnow()
            self.save()
            time.sleep(self.sync_interval)
    def update_local2sf(self):
        obj_list = SFObject.objects.filter(local2sf_sync=True)
        #check if last update is greater then current time.
        for o in obj_list:
            if not  o.local2sf_last_update:
                o.local2sf_last_update=o.get_min_update()
            next_update = o.local2sf_last_update+datetime.timedelta(seconds=o.local2sf_interval)  
            if datetime.datetime.utcnow() > next_update:
                o.synch_local2sf()
        #updates local changes to SF
    def update_sf2local(self):
        obj_list = SFObject.objects.filter(sf2local_sync=True)
        #check if last update is greater then current time.
        for o in obj_list:
            if not  o.sf2local_last_update:
                o.sf2local_last_update=o.get_min_update()
            next_update = o.sf2local_last_update+datetime.timedelta(seconds=o.sf2local_interval)  
            if datetime.datetime.utcnow() > next_update:
                o.synch_sf2local()
    def get_interval(self):
        #gets lowest interval from sf_object
        pass

    def is_running(self):
        print datetime.datetime.utcnow()-datetime.timedelta(seconds=TASK_TIME_CONS+self.sync_interval)
        if self.last_sync > datetime.datetime.utcnow()-datetime.timedelta(seconds=TASK_TIME_CONS+self.sync_interval):
            return True
        else:
            return False
        #Update SF changes to local database
#SyncProc should be a singelton 
def get_SyncProc():
    try:
        return SyncProc.objects.all()[0]
    except:
        syncp=SyncProc()
        syncp.save()
        return syncp
    